package com.otp.model.user.dao.impl;

import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;
import org.appfuse.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.otp.model.user.dao.User1Dao;

public class User1DaoHibernate extends GenericDaoHibernate<User,Long> implements User1Dao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public User1DaoHibernate() {
		super(User.class);
	}
	
	@SuppressWarnings("unchecked")
	public User getUserByUsername(String username){
		List<User> result=null;
		String query = "from User where username=?";
		result = (List<User>) getHibernateTemplate().find(query,username);
		if (result!=null&&!result.isEmpty()) return result.get(0);
		else return null;
	}
	
	@SuppressWarnings("unchecked")
	public User getUserByEmail(String email){
		List<User> result=null;
		String query = "from User where email=?";
		result = (List<User>) getHibernateTemplate().find(query,email);
		if (result!=null&&!result.isEmpty()) return result.get(0);
		else return null;
	}
	
	public void updateUser(User user) throws Exception{	
		 Session s = sessionFactory.openSession();
		 Transaction tx = null;
		 try {
		     tx = s.beginTransaction();
		     s.saveOrUpdate(user);//Check what happens when replaced by s.update() TODO
		     tx.commit();
		 }
		 catch (Exception e) {
		     if (tx!=null) tx.rollback();
		     throw e;
		 }
		 finally {
		     s.close();
		 }
	}
	
	public void addUser(User user) throws Exception{
		
		 Session s = sessionFactory.openSession();
		 Transaction tx = null;
		 try {
		     tx = s.beginTransaction();
		     s.save(user);
		     tx.commit();
		 }
		 catch (Exception e) {
		     if (tx!=null) tx.rollback();
		     throw e;
		 }
		 finally {
		     s.close();
		 }
	}

}
